package com.wondersgroup.wuhan_demo.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wondersgroup.wuhan_demo.Constant;
import com.wondersgroup.wuhan_demo.MyApplication;
import com.wondersgroup.wuhan_demo.R;
import com.wondersgroup.wuhan_demo.base.BaseFragment;
import com.wondersgroup.wuhan_demo.entity.VoiceEntity;
import com.wondersgroup.wuhan_demo.net.MyCallbackBean;
import com.wondersgroup.wuhan_demo.net.OkHttpHelper;
import com.wondersgroup.wuhan_demo.net.Param;
import com.wondersgroup.wuhan_demo.util.FileUtil;
import com.wondersgroup.wuhan_demo.util.IdCardUtil;
import com.wondersgroup.wuhan_demo.util.SPUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import org.dom4j.Element;

import java.util.Vector;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.mrobot.pkgcore.cookyplus.barcodescanner.BarcodeScanner;
import cn.mrobot.pkgcore.cookyplus.barcodescanner.ScannerListener;
import cn.mrobot.pkgcore.core.ErrorCode;
import okhttp3.Call;
import okhttp3.MediaType;

public class ScanInfoFragment extends BaseFragment {
    Unbinder unbinder;
    @BindView(R.id.rv)
    RelativeLayout rv;
    private String TAG = this.getClass().getSimpleName();
    VoiceEntity voiceEntity;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.tv_sfzhm)
    TextView tvSfzhm;
    @BindView(R.id.tv_xm)
    TextView tvXm;
    @BindView(R.id.tv_xb)
    TextView tvXb;
    @BindView(R.id.ll_user_info)
    RelativeLayout llUserInfo;
    String normValue;

    private volatile boolean isOpen=false;//是否扫码灯在打开状态

    private BarcodeScanner mBarcodeScanner;
    private ScannerListener mScannerListener = new ScannerListener() {
        @Override
        public void onGetVersion(String version) {
            Log.i(TAG, "onGetVersion: " + version);
        }

        @Override
        public void onScanned(String data) {
            Log.i(TAG, "onScanned: " + data);
            if (!TextUtils.isEmpty(data)) {
                if (handler!=null) {
                    handler.removeMessages(RESCANCODE);
                }
                numStr = data;
                boolean analyze= FileUtil.analyzeFile(getContext());
                if (analyze) {
                    getAuthKey(Constant.orgCode, Constant.userName, Constant.passWord);
                }
            }
        }

        @Override
        public void onScannerError(ErrorCode errorCode) {
            Log.i(TAG, "onScannerError: " + errorCode.getCode() + " , " + errorCode.getMessage());
        }
    };
//    private String orgCode = "31000013";
//    private String userName = "31000013";
//    private String passWord = "1234abcd_";
//    private String orgCode = "441355122";
//    private String userName = "441355122";
//    private String passWord = "123456a_";
    private String numStr = "";

    private final int SCANCODE = 0x123;
    private final int RESCANCODE = 0x124;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SCANCODE:
                    Log.i("open===","open"+MyApplication.isScanInit);
                    if (MyApplication.getInstance().isScanInit) {
                        if (mBarcodeScanner != null) {
                            mBarcodeScanner.open();
                            handler.sendEmptyMessageDelayed(RESCANCODE, 30 * 1000);
                        }
                    }else {
                        handler.sendEmptyMessageDelayed(SCANCODE, 1000);
                    }
                    break;
                case RESCANCODE:
                    setTvTip("扫描等待超时，请点击屏幕重新扫描!");
                    break;
            }


        }

    };

    public static ScanInfoFragment newInstance(String normValue) {
        Bundle args = new Bundle();
        args.putString("normValue", normValue);
        ScanInfoFragment fragment = new ScanInfoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            normValue = getArguments().getString("normValue");
            Log.i("normValue======", normValue + "");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main, container, false);
        unbinder = ButterKnife.bind(this, view);
        setTipVisible();
        setTvTip("请出示电子健康卡二维码并扫描");

        initBarcodeScanner();
//        handler.sendEmptyMessageDelayed(SCANCODE, 5000);
//            initBarcodeScanner();
//            getAuthKey(orgCode, userName, passWord);

        return view;
    }

    private void setTvTip(String tip) {
        tvTip.setText(tip);
    }

    @Override
    public void onResume() {
        super.onResume();
        LaunchActivity launchActivity = (LaunchActivity) getActivity();
        launchActivity.setTopPosition(1);
    }


    private void setTipVisible() {
        rv.setVisibility(View.VISIBLE);
        llUserInfo.setVisibility(View.GONE);
    }

    private void setUserInfoVisible() {
        rv.setVisibility(View.GONE);
        llUserInfo.setVisibility(View.VISIBLE);
    }

    private void initBarcodeScanner() {
        mBarcodeScanner = BarcodeScanner.get();
        mBarcodeScanner.setListener(mScannerListener);
//        mBarcodeScanner.open();
        Log.i("isScanInit",MyApplication.isScanInit+"");
        if (MyApplication.isScanInit) {
            handler.sendEmptyMessageDelayed(SCANCODE, 0);
        }else {
            handler.sendEmptyMessageDelayed(SCANCODE, 1000);
        }

    }

    private void getAuthKey(final String orgCodeStr, String userName, String passWord) {
        Vector v = new Vector<Param>();
        v.add(new Param("orgCode", orgCodeStr));
        v.add(new Param("userName", userName));
        v.add(new Param("passWord", passWord));
        OkHttpUtils.postString()
                .url(Constant.URL)
                .tag(TAG)
                .headers(OkHttpHelper.getHeaders())
                .mediaType(MediaType.parse("text/xml;charset=UTF-8"))
                .content(OkHttpHelper.requestContent(v, "getAuthKey"))
                .build()
                .execute(new MyCallbackBean<Element>() {
                    @Override
                    public void onError(Call call, Exception e) {
                        e.printStackTrace();
                        setTvTip("获取信息失败！请返回重试");
                    }

                    @Override
                    public void onResponse(Element response) {
                        if (response != null) {
                            String message = response.element("message").getText();
                            String resultCode = response.element("resultCode").getText();
                            if ("10000".equals(resultCode)) {
                                String authKey = response.element("authKey").getText();
                                Log.i("authKey", authKey);
                                getInfo(orgCodeStr, authKey, "5", numStr);
                            } else {
                                setTvTip(message+",可点击屏幕重新扫描！");
                            }
                        }

                    }
                });
    }

    private void getInfo(String orgCodeStr, String authKey, String type, String numStr) {
        Vector v = new Vector<Param>();
        v.add(new Param("orgCode", orgCodeStr));
        v.add(new Param("authKey", authKey));
        v.add(new Param("type", type));
        v.add(new Param("numStr", numStr));
        OkHttpUtils.postString()
                .url(Constant.URL)
                .tag(TAG)
                .headers(OkHttpHelper.getHeaders())
                .mediaType(MediaType.parse("text/xml;charset=UTF-8"))
                .content(OkHttpHelper.requestContent(v, "getInfo"))
                .build()
                .execute(new MyCallbackBean<Element>() {
                    @Override
                    public void onError(Call call, Exception e) {
                        e.printStackTrace();
//                        toast("获取个人信息失败！");
                        setTvTip("获取信息失败！点击屏幕重试");
                    }

                    @Override
                    public void onResponse(Element response) {
                        if (response != null) {
                            String message = response.elementText("message");
                            String resultCode = response.elementText("resultCode");
                            if ("10000".equals(resultCode)) {
                                Element cardInfo = response.element("cardInfo");
                                Element peopleInfo = cardInfo.element("peopleInfo");
                                String kh = cardInfo.elementText("kh");
                                Log.i("kh==", kh);
                                SPUtils.put(MyApplication.getContextObject(), getString(R.string.kh), kh);
                                if (peopleInfo != null) {
                                    setUserInfoVisible();
                                    String sfzhm = peopleInfo.elementText("sfzhm");
                                    String xm = peopleInfo.elementText("xm");
                                    String xb = peopleInfo.elementText("xb");
                                    if ("1".equals(xb)) {
                                        xb = "男";
                                    } else if ("2".equals(xb)) {
                                        xb = "女";
                                    }

                                    SPUtils.put(MyApplication.getContextObject(), getString(R.string.xm), xm);
                                    SPUtils.put(MyApplication.getContextObject(), getString(R.string.xb), xb);
                                    tvSfzhm.setText(IdCardUtil.tmIdCard(sfzhm));
                                    tvXm.setText(xm);
                                    tvXb.setText(xb);
                                    Log.i("xx==", sfzhm + "," + xm + "," + xb);
//                                  String nl=peopleInfo.elementText("")

                                }
                            } else {
                                setTvTip(message+",可点击屏幕重新扫描！");
                            }
                        }

                    }
                });
    }


//    @OnClick(R.id.btn_print)
//    public void onViewClicked() {
//        startActivity(new Intent(ScanInfoFragment.this, PayFragment.class));
//    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mBarcodeScanner != null) {
            mBarcodeScanner.close();
        }
        unbinder.unbind();
    }

    @OnClick({R.id.rv, R.id.btn_sure_fk})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rv:
                mBarcodeScanner.open();
                break;
            case R.id.btn_sure_fk:
                addFragment(DeptSelectFragment.newInstance(normValue));
                break;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mBarcodeScanner!=null) {
            mBarcodeScanner.close();
            mBarcodeScanner=null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (handler!=null){
            handler.removeCallbacksAndMessages(null);
        }
        if (mBarcodeScanner!=null) {
            mBarcodeScanner.close();
            mBarcodeScanner=null;
        }

    }

//    @OnClick(R.id.btn_scan)
//    public void onViewClicked() {
//        mBarcodeScanner.open();
//    }
}
